package cn.iocoder.yudao.framework.datapermission.v2;

import cn.iocoder.yudao.framework.common.biz.permission.PermissionCommonApi;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;

/**
 * 通用的数据权限自动配置
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Slf4j
@AutoConfiguration
@ConditionalOnClass(LoginUser.class)
@ConditionalOnBean(value = {PermissionCommonApi.class, DataPermissionScopeProvider.class})
public class DataPermissionAutoConfiguration {

    @Bean
    public DataPermissionManager dataPermissionManager(MybatisPlusInterceptor interceptor) {
        DataPermissionManager dataPermissionManager = new DataPermissionManager();
        DataPermissionInterceptor inner = new DataPermissionInterceptor(dataPermissionManager);
        // 需要加在首个，主要是为了在分页插件前面。这个是 MyBatis Plus 的规定
        MyBatisUtils.addInterceptor(interceptor, inner, 0);
        log.debug("[DataPermissionManager] init success");
        return dataPermissionManager;
    }

    @Bean
    public DataPermissionScopeProvider dataPermissionScopeProvider() {
        log.debug("[DefaultDataPermissionScopeProvider] init success");
        return new DefaultDataPermissionScopeProvider();
    }

}
